/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.common.base.office.util;

import com.alibaba.fastjson2.JSONArray;
import com.je.common.base.DynaBean;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.StringUtil;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class OfficeUtil {
    /***
     *功能描述
     * 格式化数据
     * @author wenzhe.zhou
     * @date 2020/5/29
     * @param dynaBeans
     * @return java.util.Map
     */
    public static Map getDataFormatting(List<DynaBean> dynaBeans, String key){
        Map<String,List<DynaBean>> resultMap = new HashMap<>(16);
        if (dynaBeans!=null&&dynaBeans.size()!=0){
            dynaBeans.stream().forEach(dynaBean -> {
                String keyValue = dynaBean.getStr(key);
                List<DynaBean> dynaBeanMapList = resultMap.get(keyValue);
                if (dynaBeanMapList!=null&&dynaBeanMapList.size()!=0){
                    dynaBeanMapList.add(dynaBean);
                }else {
                    dynaBeanMapList = new ArrayList<>(16);
                    dynaBeanMapList.add(dynaBean);
                    resultMap.put(keyValue,dynaBeanMapList);
                }
            });
        }
        return resultMap;
    }



    public static Map getDataFormattingDynaBean(List<DynaBean> dynaBeans, String key){
        Map<String,Object> resultMap = new HashMap<>(16);
        if (dynaBeans!=null&&dynaBeans.size()!=0){
            dynaBeans.stream().forEach(dynaBean -> {
                String keyValue = dynaBean.getStr(key);
                DynaBean dynaBeanMap = (DynaBean) resultMap.get(keyValue);
                if (dynaBeanMap==null){
                    resultMap.put(keyValue,dynaBean);
                }
            });
        }
        return resultMap;
    }




    /***
     *功能描述
     * 日期加一天
     * @author wenzhe.zhou
     * @date 2020/5/29
     * @param date
     * @return void
     */
    public static Date setDateChange(Date date){
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
        date=calendar.getTime();
        return date;
    }



    /***
     *功能描述
     *判断d1,d2时间段在不在开始时间和结束时间内
     * @author wenzhe.zhou
     * @date 2020/6/1
     * @param date1
     * @param date2
     * @param startTime
     * @param endDate
     * @return java.lang.Boolean
     */
    public static Boolean jssjCz(Date date1, Date date2, Date startTime, Date endDate){
        if (date1 == null || date2 == null || startTime == null || endDate == null){
            return false;
        }
        long d1 = date1.getTime();
        long d2 = date2.getTime();
        long v = d2 - d1;
        long start = startTime.getTime();
        long end = endDate.getTime();
        if ((d1<end) && (start<d2)) {
            return true;
        } else if (v > 7200000) {  //2小时等于 7200000毫秒
            return false;
        } else {
            return false;
        }
    }


    /****
     * 获取日期中的时间
     * @param dateStr
     * @return
     */
    public static String getRqTime(String dateStr){
        Date date = null;
        if (!dateStr.contains("-")){
            date = DateUtils.getDate("2020-01-01"+" "+dateStr+":00", DateUtils.DAFAULT_DATETIME_FORMAT);
        }else {
            date = DateUtils.getDate(dateStr, DateUtils.DAFAULT_DATETIME_FORMAT);
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);					//放入Date类型数据
        int Hh = calendar.get(Calendar.HOUR_OF_DAY);			//时（24小时制）
        int Mm = calendar.get(Calendar.MINUTE);					//分
        int Ss = calendar.get(Calendar.SECOND);					//秒
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String time = Hh+":"+Mm+":00";

        try {
            time = sdf.format(sdf.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }



    /****
     * 两时间之间相差的小时数
     * @param startDate
     * @param endDate
     * @return
     */
    public static Double getStartToEndTime(Date startDate, Date endDate) {
        if (startDate == null || endDate == null)
        {
            return null;
        }
        Long interval = endDate.getTime() - startDate.getTime();
        interval = interval / (60 * 60 * 1000);
        return interval.doubleValue();
    }


    /****
     * 两时间之间相差的小时数
     * @param startDate
     * @param endDate
     * @return
     */
    public static Map getQjTimeStr(Date startDate, Date endDate) {
        if (startDate == null || endDate == null)
        {
            return null;
        }
        Map<String,Object> map = new HashMap<>(16);
        map.put("startDate", DateUtils.formatDate(startDate, DateUtils.DAFAULT_DATETIME_FORMAT));
        map.put("endDate", DateUtils.formatDate(endDate, DateUtils.DAFAULT_DATETIME_FORMAT));
        return map;
    }

    /**
     *判断时间是否在某个时间段内
     * @param nowTime   要比较的时间
     * @param beginTime   开始时间
     * @param endTime   结束时间
     * @return   true在时间段内，false不在时间段内
     * @throws Exception
     */
    public static Boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if (date.after(begin) && date.before(end)) {
            return true;
        } else if (nowTime.compareTo(beginTime) == 0 || nowTime.compareTo(endTime) == 0) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * Boolean转化
     * @param yesOrNo
     * @return
     */
    public static String getStatusByBoolean(Boolean yesOrNo){
        if (yesOrNo){
            return "1";
        }
        return "0";
    }

    /****
     * 数字字符串转化：8.00-->8、8.5-->8.5
     * @param nums
     * @return
     */
    public static String getDoubleString(String nums) {
        StringBuilder numberBuilder = new StringBuilder();
        if (StringUtil.isNotEmpty(nums)){
            String [] numArr = nums.split(",");
            for (String num:numArr){
                String numberStr;
                double number = 0.00d;
                if (StringUtil.isEmpty(num)){
                    num = "0.00";
                }
                number = Double.parseDouble(num);
                if (((int) number * 1000) == (int) (number * 1000)) {
                    //如果是一个整数
                    numberStr = String.valueOf((int) number);
                } else {
                    DecimalFormat df = new DecimalFormat("######0.0");
                    numberStr = df.format(number);
                }
                numberBuilder.append(numberStr);
                numberBuilder.append(",");
            }
            numberBuilder.deleteCharAt(numberBuilder.length()-1);
        }
        return numberBuilder.toString();
    }

    /****
     * 判断某个时间是否是工作日
     * @param dateTime
     * @param jqgls
     * @return
     */
    public static Boolean isGzr(String dateTime,List<DynaBean> jqgls){
        Boolean isGzr = false;
        String xq = DateUtils.dateToWeek(dateTime);
        if (xq.equals("星期六")||xq.equals("星期日")){
            isGzr = true;
            return isGzr;
        }
        for (DynaBean jqgl:jqgls){
            String ksrq = jqgl.getStr("JQGL_KSRQ");
            String jsrq = jqgl.getStr("JQGL_JSRQ");
            Boolean isCz = belongCalendar(DateUtils.getDate(dateTime), DateUtils.getDate(ksrq), DateUtils.getDate(jsrq));
            if (isCz){
                isGzr = true;
                break;
            }
        }
        return isGzr;
    }

    /***
     * 根据每周的第一天，取得本月的第一天和最后一天（跨周）
     * @param weekFirstDay
     * @return
     */
    public static Map<String,String> getFirstDayAndEndDayToMonthByWeekFirst(Date weekFirstDay){
        Map<String,String> resultMap = new HashMap<>();
        if (weekFirstDay!=null){
            //当前年
            String year = DateUtils.formatDate(weekFirstDay, "yyyy");
            //当前月
            int month = weekFirstDay.getMonth()+1;
            //本年月的第一天
            int firstMonthDay = DateUtils.getFirstDayOfMonth(Integer.parseInt(year),month);
            //本年月的最后一天
            int endMonthDay = DateUtils.getLastDayOfMonth(Integer.parseInt(year),month);
            //本月中所有为周一的日期
            List<Date> firstWeekDates = new ArrayList<>(16);
            for (int i=firstMonthDay;i<=endMonthDay;i++){
                boolean isTrue = DateUtils.isFirstDayOfWeek(DateUtils.newCalendar(i));
                if (isTrue){
                    Date firstWeekDay = DateUtils.getDate(i);
                    firstWeekDates.add(firstWeekDay);
                }
            }
            Date firstDay = firstWeekDates.get(0);
            Date lastDay = firstWeekDates.get(firstWeekDates.size()-1);
            lastDay.setDate(lastDay.getDate()+6);
            resultMap.put("firstDate", DateUtils.formatDate(firstDay));
            resultMap.put("lastDay", DateUtils.formatDate(lastDay));
        }
        return resultMap;

    }
    public static Map<String,String> getDynaMap(DynaBean dynaBean){
        HashMap<String,Object> vals=dynaBean.clone().getValues();
        Map<String,String> results=new HashMap<>();
        for(String key:vals.keySet()){
            results.put(key,vals.get(key)+"");
        }
        return results;
    }
    public static Map<String,String> getMapVals(Map<String,Object> vals){
        Map<String,String> results=new HashMap<>();
        for(String key:vals.keySet()){
            results.put(key,vals.get(key)+"");
        }
        return results;
    }
    public static String getFileTypeSuffix(String filePath){
        String fileType="";
        if(StringUtil.isNotEmpty(filePath)){
            int lastIndex=filePath.lastIndexOf(".");
            if(lastIndex!=-1){
                fileType=filePath.substring(lastIndex+1);
            }
        }
        return fileType;
    }
    public static String getFileKey(String fileVal){
        JSONArray files=new JSONArray();
        String fileKey="";
        if(StringUtil.isNotEmpty(fileVal)){
            files=JSONArray.parseArray(fileVal);
        }
        if(files.size()>0){
            fileKey=files.getJSONObject(0).getString("fileKey");
        }
        return fileKey;
    }
}
